package com.seo.pojo;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import lombok.Data;

/**
 * 数据类型
 * 
 * @author shibeilei
 * @version 2017.12.13 11:42
 */
@Data
public class InputBody implements Serializable {

	private static final long serialVersionUID = -4092720936269867892L;
	private Map<String, Object> params;

	@SuppressWarnings("unchecked")
	public <T> T get(String key, Class<T> type) {
		return (T) params.get(key);
	}

	public void put(String key, Object value) {
		params.put(key, value);
	}

	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	public InputBody() {
		HttpServletRequest request = getRequest();
		params = new HashMap<>();
		Map<String, String[]> properties = request.getParameterMap();
		Iterator<Map.Entry<String, String[]>> entries = properties.entrySet().iterator();
		Map.Entry<String, String[]> entry;
		String name = "";
		while (entries.hasNext()) {
			entry = entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				params.put(name, "");
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				if (values.length == 1) {
					params.put(name, values[0]);
				} else {
					params.put(name, values);
				}

			}

		}
	}

	public static InputBody init() {
		return new InputBody();
	}
}
